package com.coollang.smartbra.activity;

import android.app.ProgressDialog;
import android.bluetooth.BluetoothAdapter;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Handler;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.coollang.smartbra.MyAutoLayoutActivity;
import com.coollang.smartbra.R;
import com.coollang.smartbra.adapter.DeviceListAdapter;
import com.coollang.smartbra.base.MyApplication;
import com.coollang.smartbra.bleutil.BleUtil;
import com.coollang.smartbra.bleutil.callback.BleCallbackImpl;
import com.coollang.smartbra.fragment.FirstFragment;
import com.coollang.smartbra.presenter.SearchActivityPresenter;
import com.coollang.smartbra.utils.NetUtils;
import com.coollang.smartbra.utils.ToastUtils;
import com.coollang.smartbra.utils.TranslucentSystemBarUtils;
import com.coollang.smartbra.utils.UIUtils;
import com.coollang.smartbra.views.OptionCircle;
import com.inuker.bluetooth.library.search.SearchResult;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;


/**
 * @author Timmy
 *         蓝牙设备搜索页面
 */
public class SearchActivity extends MyAutoLayoutActivity {

    private static final String TAG = "SearchActivity";
    private static final int ACCESS_FINE_LOCATION_REQUEST_CODE = 666;
    @BindView(R.id.tv_title)
    TextView tvTitle;
    @BindView(R.id.blelist)
    RecyclerView blelist;
    @BindView(R.id.iv_back)
    ImageView mIvBack;
    @BindView(R.id.status_bar)
    View statusBar;
    @BindView(R.id.content)
    RelativeLayout content;
    @BindView(R.id.cicleview)
    OptionCircle mCicleview;
    @BindView(R.id.tv_search)
    TextView mTvSearch;
    @BindView(R.id.reg_req_code_gif_view)
    RelativeLayout miOSLoading;
    @BindView(R.id.tv_search_again)
    TextView mSearchView;

    private BleUtil mBleUtil;
    public DeviceListAdapter mDeviceListAdapter;
    private Handler mHandler = new Handler();
    private ProgressDialog mProgressDialog;
    private SearchActivityPresenter mPresenter;

    @Override
    protected void initView() {
        setContentView(R.layout.activity_search);
        ButterKnife.bind(this);
        TranslucentSystemBarUtils.showChenJinZhuangTaiLan(statusBar, this, content);
        findViewByIds();

        mIvBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finishAct();
            }
        });
    }

    private void findViewByIds() {
        tvTitle.setText(getString(R.string.search_device));
        tvTitle.setTextColor(getResources().getColor(R.color.black_80));
        tvTitle.setTextSize(16);
        mDeviceListAdapter = new DeviceListAdapter(this);
        blelist.setAdapter(mDeviceListAdapter);
        blelist.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false));
    }

    @Override
    protected void initData() {
        mPresenter = new SearchActivityPresenter(this);
        mPresenter.queryDeviceList();

        mBleUtil = BleUtil.getInstance();
        mBleUtil.registerNotifyListener(mBleNotifyListener);

        // 查询用户是否有绑定设备
        checkBluetooth();
    }

    /**
     * 是否连接的是自己绑定的设备
     */
    private boolean isConnectBind;

    public void checkBluetooth() {
        // 如果设备支持ble
        if (BleUtil.getInstance().isBleSupported()) {
            // 判断蓝牙是否打开
            boolean bluetoothOpened = BleUtil.getInstance().isBluetoothOpened();
            if (!bluetoothOpened) {
                // 打开蓝牙
                turnOnBluetooth();
            } else {
                // 去扫描设备
                boolean decviceConnected = BleUtil.getInstance().isDecviceConnected();
                if (!decviceConnected) {
                    scanDevice();
                }
            }
        } else {
            Toast.makeText(this, R.string.no_bluetooth, Toast.LENGTH_LONG).show();
        }
    }

    /**
     * 弹出系统弹框提示用户打开 Bluetooth
     */
    private void turnOnBluetooth() {
        // 请求打开 Bluetooth
        Intent requestBluetoothOn = new Intent(
                BluetoothAdapter.ACTION_REQUEST_ENABLE);

        // 设置 Bluetooth 设备可以被其它 Bluetooth 设备扫描到
        requestBluetoothOn
                .setAction(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);

        // 请求开启 Bluetooth
        startActivityForResult(requestBluetoothOn,
                ACCESS_FINE_LOCATION_REQUEST_CODE);
    }

    private void showProgressDialog(String title, String message) {
        if (mProgressDialog == null) {
            mProgressDialog = ProgressDialog.show(SearchActivity.this, title, message, false);
        } else if (mProgressDialog.isShowing()) {
            mProgressDialog.setTitle(title);
            mProgressDialog.setMessage(message);
        }
        mProgressDialog.show();
    }

    private void hideProgressDialog() {
        if (mProgressDialog != null && mProgressDialog.isShowing()) {
            mProgressDialog.dismiss();
            mProgressDialog = null;
        }
    }

    /**
     * 关闭当前页面
     */
    private void finishAct() {
        mBleUtil.unRegisterNotifyListener();
        mBleUtil.stopSearch();
        mCicleview.stopAnimation();
        finish();
        overridePendingTransition(0, R.anim.push_down_out);
    }

    // =================================== 蓝牙操作相关 =================================

    /**
     * 扫描设备
     */
    private void scanDevice() {
        mCicleview.startCountdown();
        mBleUtil.search();
    }

    private SearchResult mSearchResult;

    /**
     * 连接设备
     */
    public void connectDevice(SearchResult searchResult) {
        mSearchResult = searchResult;
        mBleUtil.stopSearch();

        if (!NetUtils.hasNet(UIUtils.getContext())) {
            ToastUtils.showToast(UIUtils.getString(R.string.no_net));
        } else {
            showProgressDialog("连接设备", "正在连接");

            // 判断连接的是不是自己绑定的设备
            if (mPresenter.checkIsBind(searchResult.getAddress().replace(":", ""))) {
                isConnectBind = true;
                toConnectDevice();
            } else {
                isConnectBind = false;
                mPresenter.setIsBindingInfoInfo(searchResult.getAddress());
            }
        }
    }

    /**
     * 去连接设备
     */
    private void toConnectDevice() {
        // 连接
        mBleUtil.connect(mSearchResult.getAddress());
    }

    /**
     * 需要重新开始搜索
     */
    public void reStartSearch() {

        mDeviceListAdapter.setShowNoDeviceUI(false);
        mSearchView.setVisibility(View.GONE);
        mBleUtil.stopSearch();
        // 清空集合
        mDeviceListAdapter.cleanData();
        scanDevice();
    }

    /**
     * 蓝牙交互接口回调
     */
    BleCallbackImpl mBleNotifyListener = new BleCallbackImpl() {

        @Override
        public void onSearchStarted() {
            mTvSearch.setText("正在搜索...");
        }

        @Override
        public void onScan(SearchResult result) {
            //添加设备
            mDeviceListAdapter.addDevice(result);
        }

        @Override
        public void onScanStop() {
            mDeviceListAdapter.scanStop();
            mSearchView.setVisibility(View.VISIBLE);
            if (mDeviceListAdapter.getItemCount() == 1) {
                mDeviceListAdapter.setShowNoDeviceUI(true);
                mTvSearch.setText("未搜索到设备");
            } else {
                mCicleview.stopAnimation();
                mTvSearch.setText("搜索已完成,点击列表连接设备");
                int itemCount = mDeviceListAdapter.getItemCount();
                if (itemCount == 2) {
                    // 如果只有一个设备, 直接去连接
                    connectDevice(mDeviceListAdapter.getPositionData(0));
                }
            }
        }

        @Override
        public void onBleConnected() {
            MyApplication.getApplication().sendDate();// 校准时间戳
            MyApplication.getApplication().isConnected = true;
            MyApplication.getApplication().deviceName = mSearchResult.getName();
            MyApplication.getApplication().deviceMac = mSearchResult.getAddress();

            //连上设备
            FirstFragment.imgvDeviceRight.setImageResource(R.drawable.device_connect);
            //连上设备绑定设备
            // 绑定设备
            if (!isConnectBind) {
                mPresenter.bindDevice(mSearchResult.getAddress());
            }

            mHandler.postDelayed(new Runnable() {
                @Override
                public void run() {
                    dissMiss();
                    finishAct();
                }
            }, 500);
        }

        @Override
        public void onBleDisconnected() {
            hideProgressDialog();
            // 连接失败
            FirstFragment.imgvDeviceRight.setImageResource(R.drawable.device_disconnect);
            MyApplication.getApplication().isConnected = false;
            dissMiss();
        }
    };

    // =================================== UI 交互 ==============================================


    private void dissMiss() {
        hideProgressDialog();
    }

    /**
     * 设备已经被他人绑定弹窗
     */
    private void showNOBleDialog() {
        new AlertDialog.Builder(this)
                .setTitle(getString(R.string.isbinded))
                .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        // 点击事件的回调方法
                        dialog.dismiss();
                    }
                }).show();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == ACCESS_FINE_LOCATION_REQUEST_CODE) {
            if (resultCode == RESULT_CANCELED) {
                Toast.makeText(this, "不允许蓝牙开启", Toast.LENGTH_SHORT).show();
                finishAct();
            } else {
                scanDevice();
            }
        }
    }

    @OnClick(R.id.tv_search_again)
    public void onViewClicked() {
        reStartSearch();
    }

    public void onCheckSucceed(int data) {
        if (data == 0 || data == 1) {
            // 没有被绑定
            // 判断自己是否有绑定设备
            if (mPresenter.mDeviceModel == null) {
                // 说明没有绑定设备
                toConnectDevice();
            } else {
                // 说明有绑定设备 去解绑之前的
                mPresenter.unBindDevice(mPresenter.mDeviceModel.getDeviceMac());
            }
        } else if (data == 2) {
            // 被他人绑定
            showNOBleDialog();
            dissMiss();
        }
    }

    public void unBindSucceed() {
        toConnectDevice();
    }

    public void stopScan() {
        BleUtil.getInstance().stopSearch();
    }
}
